
package tjs.styudy.mini.springboot.devtools.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.Thread.UncaughtExceptionHandler;

class SilentExitExceptionHandler implements UncaughtExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(SilentExitExceptionHandler.class);
    private final UncaughtExceptionHandler delegate;

    SilentExitExceptionHandler(UncaughtExceptionHandler delegate) {
        this.delegate = delegate;
    }

    @Override
    public void uncaughtException(Thread thread, Throwable exception) {
        if (exception instanceof SilentExitException) {
            logger.warn(exception.getMessage());
            return;//SilentExitException 不打印
        }
        if (this.delegate != null) {
            this.delegate.uncaughtException(thread, exception);
        }
    }

    public static UncaughtExceptionHandler extendThreadOldHandler(Thread thread) {
        UncaughtExceptionHandler handler = thread.getUncaughtExceptionHandler();
        if (!(handler instanceof SilentExitExceptionHandler)) {
            handler = new SilentExitExceptionHandler(handler);
            thread.setUncaughtExceptionHandler(handler);
        }
        return handler;
    }

    static void exitCurrentThread(String err) {
        throw new SilentExitException(err);
    }

    private static class SilentExitException extends RuntimeException {
        public SilentExitException(String err) {
            super(err);
        }
    }

}
